var util = require("util");
var async = require("async");
var mysql = require('mysql');

function succeed(response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end();
}

function createDBInstance() {
    return mysql.createConnection({
	host     : 'localhost',
	user     : 'root',
	password : 'zjzdw7980',
	database : 'mydesktop',
    });
 }

function insertDB(response, postData) {
    var connection = createDBInstance();
    var async = require("async");
    async.series([
	connection.connect.bind(connection),
	async.apply(connection.query.bind(connection),
		    "CREATE TABLE IF NOT EXISTS concepts ("+
		    "name VARCHAR(64) NOT NULL,"+
		    "priority INT NOT NULL DEFAULT 0,"+
		    "date DATE NOT NULL,"+
		    "notes VARCHAR(256),"+
		    "PRIMARY KEY (name))"),
	async.apply(connection.query.bind(connection),
		    "INSERT INTO concepts VALUES('" +
		    postData["word"] + "',0,CURDATE(),'')"),
	connection.end.bind(connection)
    ], 
    function(err, result) {
	if (err) console.error(err);
	succeed(response);
    });
}

function upload(response, postData) {
    if (postData["word"] != null)
	insertDB(response, postData);
    else
	succeed(response);
}

function fetch(response, postData) {
    var connection = createDBInstance();

    response.writeHead(200, {"Content-Type": "text/plain"});
    async.series([
	connection.connect.bind(connection),
	function(callback) {
	    connection.query(
		"SELECT * FROM concepts ORDER BY RAND() LIMIT 1",
		function(err, rows) {
		    if (!err) response.write(JSON.stringify(rows));
		}
	    );
	    callback(null, null);
	},
	connection.end.bind(connection)
    ], 
    function(err, result) {
	if (err) console.error(err);
	response.end();
    });
}

function error(response) {
    response.writeHead(404, {"Content-Type": "text/html"});
    response.write("404 Not Found");
    response.end();
}

exports.upload = upload;
exports.fetch = fetch;
exports.error = error;
